package severlet;

import service.DormadminService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "AdminLoginServlet", value = "/AdminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username == null || "".equals(username)) {
            request.setAttribute("adminEmpty", "用户名为空");
            request.getRequestDispatcher("admin_login.jsp").forward(request, response);
        }
        if (password == null || "".equals(password)) {
            request.setAttribute("psdEmpty", "密码为空");
            request.getRequestDispatcher("admin_login.jsp").forward(request, response);
        }

        //验证码判断
        String yanzhengma = request.getParameter("verifyCode");
        String code = (String) request.getSession().getAttribute("uri");
        if ("".equals(yanzhengma) || yanzhengma == null) {
            request.setAttribute("codeEmpty", "验证码为空");
            System.out.println("验证码为空");
            request.getRequestDispatcher("admin_login.jsp").forward(request, response);
        }

        if (yanzhengma.equalsIgnoreCase(code)) {

            DormadminService dormadminService = new DormadminService();
            boolean flag = dormadminService.login(request, response, username, password);
//登录验证
            if (flag== true && yanzhengma.equalsIgnoreCase(code)) {
                request.getRequestDispatcher("admin_information.jsp").forward(request, response);
            } else {
                request.setAttribute("err", "用户名或密码错误");
                request.getRequestDispatcher("admin_login.jsp").forward(request, response);
            }

        }else {
            request.setAttribute("codeErr","验证码错误");
            request.getRequestDispatcher("admin_login.jsp").forward(request,response);
        }
    }
}
